package org.momo.rpc.springboot.starter.config;

import org.momo.rpc.config.RpcConfigLoader;
import org.momo.rpc.config.config.RpcConfig;
import org.momo.rpc.extention.ExtensionLoader;
import org.momo.rpc.registry.ProviderRegistry;
import org.momo.rpc.server.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//@Configuration
public class RpcServerAutoConfig {
    @Bean
    public RpcConfig rpcConfig() {
        RpcConfigLoader.init();
        RpcConfig rpcConfig = RpcConfigLoader.getRpcConfig();
        return rpcConfig;
    }

    @Bean
    public ProviderRegistry providerRegistry(RpcConfig rpcConfig) {
        ProviderRegistry providerRegistry = ExtensionLoader.getExtensionLoader(ProviderRegistry.class).getExtension(rpcConfig.getRegistry());
        try {
            providerRegistry.initRegistryClient(rpcConfig.getRegistryConfig());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return providerRegistry;
    }

    @Bean
    public Server server(RpcConfig rpcConfig) {
        Server server = ExtensionLoader.getExtensionLoader(Server.class).getExtension(rpcConfig.getServer());
        try {
            server.start(rpcConfig.getServerPort());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return server;
    }
}
